<template>
  <div>
    <!-- 三级联动选择器 -->
    <CategorySelect
      :disabled="!isShowTable"
      @getCategoryId="getCategoryId"
      width="100%"
    ></CategorySelect>

    <el-card style="margin-top: 20px">
      <!-- 添加按钮 -->
      <el-button
        v-show="isShowTable"
        style=""
        icon="el-icon-plus"
        type="primary"
        :disabled="!categoryId.c3"
        @click="addAttr"
        >添加属性</el-button
      >
      <!-- 表格数据 -->
      <el-table
        v-show="isShowTable"
        :data="attrInfoList"
        border
        style="width: 100%"
        height="65vh"
      >
        <el-table-column type="index" label="序号" width="80" align="center">
        </el-table-column>
        <el-table-column prop="attrName" label="属性名" width="180">
        </el-table-column>
        <el-table-column label="属性值">
          <template slot-scope="{ row, $index }">
            <el-tag
              type="success"
              v-for="(data, i) in row.attrValueList"
              :key="data.id"
              style="margin: 0 10px"
              >{{ data.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="{ row }">
            <el-button type="warning" @click="editAttrInfo(row)"
              >修改</el-button
            >
            <el-button type="danger" @click="delAttrInfo(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加修改数据 -->
      <el-form
        ref="myform"
        v-show="!isShowTable"
        label-position="left"
        label-width="80px"
        :model="form"
        :rules="rules"
      >
        <el-form-item label="属性名" prop="name">
          <el-input
            v-model="form.name"
            style="width: 30%"
            @change="stringTrim(form, 'name')"
          ></el-input>
        </el-form-item>
        <el-form-item label="属性值" prop="vaule">
          <el-input
            v-model="form.vaule"
            style="width: 30%"
            @change="stringTrim(form, 'vaule')"
            @keyup.native.enter="addValue"
          ></el-input>
          <el-button type="primary" @click="addValue">添加</el-button>
        </el-form-item>
        <el-form-item label="属性列表" prop="vauleList">
          <!-- 已添加的属性列表 -->
          <el-table :data="form.vauleList" border height="60vh">
            <el-table-column
              label="序号"
              type="index"
              width="80"
            ></el-table-column>
            <el-table-column label="属性值">
              <template slot-scope="{ row, $index }">
                <el-input
                  v-if="!row.flag"
                  v-model="row.valueName"
                  size="mini"
                  :ref="$index"
                  @keyup.native.enter="row.flag = true"
                  @blur="row.flag = true"
                ></el-input>
                <el-tag v-else @click="clickTag(row, $index)" disable-transitions>{{
                  row.valueName
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{ row }">
                <el-button
                  type="danger"
                  size="mini"
                  @click="form.vauleList.splice(form.vauleList.indexOf(row), 1)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-button type="primary" @click="addAttrInfo">保存</el-button>
        <el-button type="" @click="cancel">返回</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      attrInfoList: [],
      isShowTable: true,
      rules: {
        name: [
          { required: true, message: '请输入属性名称', trigger: 'change' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'change'
          }
        ],
        vauleList: [{ required: true, message: '属性值列表不为空' }],
        vaule: [{ min: 1, max: 20, message: '长度在 1 到 20 个字符' }]
      },
      form: {
        name: '',
        vaule: '',
        vauleList: [],
        attrId: ''
      },
      categoryId: { c1: '', c2: '', c3: '' }
    }
  },
  methods: {
    // 获取属性
    async getAttrInfo() {
      const { c1, c2, c3 } = this.categoryId
      const res = await this.$API.attr.getAttrList(c1, c2, c3)
      if (res.code == 200) {
        this.attrInfoList = res.data
      }
    },
    getCategoryId(data) {
      this.categoryId = data
      this.getAttrInfo()
    },
    // 清空表单
    clearForm() {
      // 每次都赋值一个新对象
      this.form = {
        name: '',
        vaule: '',
        vauleList: [],
        attrId: ''
      }
    },
    // 点击添加按钮
    addAttr() {
      this.isShowTable = false
    },
    // 添加属性值
    addValue() {
      if (this.form.vaule.length >= 1 && this.form.vaule.length <= 20) {
        this.form.vauleList.push({
          attrId: this.form.attrId,
          valueName: this.form.vaule,
          // 添加标识,用于区分显示input 还是 tag
          flag: true
        })
        // 清空数据
        this.form.vaule = ''
      }
    },
    // 添加,修改 属性
    addAttrInfo() {
      // 表单验证
      this.$refs.myform.validate(async (valid) => {
        if (valid) {
          const { name, vauleList, attrId } = this.form
          const res = await this.$API.attr.saveAttrInfo({
            attrName: name,
            attrValueList: vauleList.filter((item) => item.valueName.trim()),
            categoryId: this.categoryId.c3,
            categoryLevel: 3,
            id: attrId || undefined
          })
          if (res.code == 200) {
            // 清空数据
            this.clearForm()
            this.$message({
              type: 'success',
              message: attrId ? '修改成功' : '添加成功'
            })
            // 从新获取列表
            this.getAttrInfo()
            this.isShowTable = true
          } else {
            this.$message({ type: 'error', message: res.data || res.message })
          }
        } else {
          this.$message({ type: 'warning', message: '请完整填写表单' })
        }
      })
    },
    // 点击编辑按钮
    editAttrInfo(data) {
      this.form.name = data.attrName
      data.attrValueList.forEach((vaule) => {
        // 添加标识,用于区分显示input 还是 tag
        this.form.vauleList.push({ ...vaule, flag: true })
      })
      this.form.attrId = data.id
      // 显示
      this.isShowTable = false
    },
    // 删除属性
    delAttrInfo(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$API.attr.delAttrInfo(id)
          if (res.code == 200) {
            this.$message({ type: 'success', message: '删除成功' })
            // 跟新列表数据
            this.getAttrInfo()
          } else {
            this.$message({ type: 'error', message: res.data || res.message })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    stringTrim(form, flag) {
      form[flag] = form[flag].trim()
    },
    cancel() {
      if (this.form.name || this.form.vauleList.length != 0) {
        this.$confirm('编辑的数据未保存, 是否继续编辑?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        })
          .then(() => {
            this.isShowTable = false
          })
          .catch(() => {
            this.clearForm()
            this.isShowTable = true
          })
      } else {
        this.isShowTable = true
      }
    },
    clickTag(row, i) {
      row.flag = false
      //需要注意：点击span的时候，显示input节点，实现自动聚焦,
      //切换为input，需要注意，对于浏览器而言，页面重绘与重拍耗时间的
      //因此我们不可能一点击span立马获取到input
      //$nextTick,当节点渲染完毕了，会执行一次
      this.$nextTick(() => {
        this.$refs[i].focus()
      })
    }
  }
}
</script>

<style></style>
